/*
 * @Descripttion: 
 * @version: 
 * @Author: lwj
 * @Date: 2022-06-14 18:56:19
 * @LastEditors: yuanliutech@lwj
 * @LastEditTime: 2023-02-20 15:11:16
 */
const app = getApp()
import Toast from '@vant/weapp/toast/toast';
import Notify from '@vant/weapp/notify/notify';
import {
  validateUsername,
  validatePwd,
  validateMobile,
} from '../../utils/validate.js'
var WXBizDataCrypt = require('../../utils/WXBizDataCrypt') //解密手机号
import {
  reqSmsCode,
  reqRegister,
  reqConsumerRegister,
  reqWxUserInfo,
  reqGetPhoneNum,
  reqLogin,
  reqUserInfo,
} from '../../request/api.js';
import {
  showMsg
} from '../../utils/config.js'

Page({

  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    srcUsername: '../../statics/images/login-register/username_icon.png',
    srcMobile: '../../statics/images/login-register/mobile_icon.png',
    srcMessage: '../../statics/images/login-register/message_icon.png',
    srcPwd: '../../statics/images/login-register/pwd_icon.png',
    srcVerify: '../../statics/images/login-register/verify_icon.png',
    srcEyeClose: '../../statics/images/login-register/eye_close_icon.png',
    srcEyeOpen: '../../statics/images/login-register/eye_open_icon.png',
    username: '',
    nickname: '',
    mobile: '',
    smsCode: '',
    pwd1: '',
    pwd2: '',
    isPassword1: true,
    isPassword2: true,
    mobileIconColor: false,
    smsCodeMobile: '', //获取短信的手机号，防止获取短信后修改手机号
    showCountDown: false, //是否展示倒计时
    countDown: '', //60s倒计时
    confirmButtonDisabled: false, //确认按钮禁用
    radio: '1',
  },

  onLoad: function (options) {

  },
  // 获取用户名
  usernameChange(e) {
    this.setData({
      username: e.detail.value,
      nickname: e.detail.value,
    })
  },
  // 清除用户名
  clearUsername() {
    this.setData({
      username: ''
    })
  },
  // 获取昵称
  nicknameChange(e) {
    this.setData({
      nickname: e.detail.value
    })
  },
  // 清除昵称
  clearNickename() {
    this.setData({
      nickname: ''
    })
  },
  // 获取手机号
  mobileChange(e) {
    this.setData({
      mobile: e.detail.value
    })
  },
  // 获取本机手机号  
  getPhoneNumber(e) {
    console.log(e.detail);
    let that = this
    wx.login({
      async success(res) {
        // console.log(res);
        // console.log(res.code,'jsCode');
        const res1 = await reqGetPhoneNum({
          code: e.detail.code
        }) //获取手机号
        console.log(res1);
        that.setData({
          mobile: res1.data.row.phone_info.phoneNumber
        })
        // 方法二获取信息自行解析
        // const res1 = await reqWxUserInfo({
        //     jsCode: res.code
        // }) //获取信息
        // console.log(res1);
        // if (res1.code !== 20000) return Toast(res1.message)
        // let {
        //     row
        // } = res1.data
        // // 解密
        // let appId = 'wxda69189aa728178c'
        // let encryptedData = e.detail.encryptedData
        // let iv = e.detail.iv
        // let pc = new WXBizDataCrypt(appId, row.session_key)
        // let data = pc.decryptData(encryptedData, iv)
        // console.log(data,'data');
        // if (!data) return Toast("获取手机号码失败，请重试")
        // let mobile = data.phoneNumber
        // that.setData({
        //     mobile
        // })
      },
    })
  },
  // 清除手机号
  clearMobile() {
    this.setData({
      mobile: ''
    })
  },

  // 获取短信验证码
  smsCodeChange(e) {
    this.setData({
      smsCode: e.detail.value
    })
  },
  /**
   * @name: 点击获取短信
   * @msg:  mobile
   * @return {*} smsCode
   */
  async getSmsCodeClick() {
    if (this.data.showCountDown) return
    let {
      mobile
    } = this.data
    if (!validateMobile(mobile)) return
    const res = await reqSmsCode({
      mobile
    })
    if (res.code != 20000) return Toast.fail(res.data.errorInfo);
    Toast("请注意查收手机短信验证码")
    this.setData({
      showCountDown: true,
      countDown: 60,
      smsCodeMobile: mobile
    })
    let intervalId = setInterval(() => {
      let {
        countDown
      } = this.data
      if (this.data.countDown > 0 && this.data.countDown <= 60) {
        countDown -= 1
        this.setData({
          countDown
        })
      } else {
        this.setData({
          showCountDown: false
        })
        clearInterval(intervalId);
        intervalId = null;
      }
    }, 1000);
  },
  // 清除短信验证码
  clearSmsCode() {
    this.setData({
      smsCode: ''
    })
  },
  // 获取密码  pwd1
  pwdChange1(e) {
    this.setData({
      pwd1: e.detail.value
    })
  },
  // 清除密码1 
  clearPwd1() {
    this.setData({
      pwd1: ''
    })
  },
  // pwd1 密码显隐
  showPwd1() {
    this.setData({
      isPassword1: !this.data.isPassword1
    })
  },
  // 获取密码  pwd2
  pwdChange2(e) {
    this.setData({
      pwd2: e.detail.value
    })
  },
  // 清除密码2
  clearPwd2() {
    this.setData({
      pwd2: ''
    })
  },
  // pwd2 密码显隐
  showPwd2() {
    this.setData({
      isPassword2: !this.data.isPassword2
    })
  },
  /**
   * @name: 确定注册
   * @msg: 
   * @return {*}
   */
  async registerConfirm() {
    if (this.data.confirmButtonDisabled) return
    let {
      username,
      nickname,
      pwd1,
      pwd2,
      mobile,
      smsCode,
      smsCodeMobile,
      radio
    } = this.data
    // if (!validateUsername(username)) return
    if (!validatePwd(pwd1)) return
    // if (pwd1 !== pwd2) return Toast("两次密码不一样")
    if (!smsCode) return Toast("请填写短信验证码")
    if (smsCodeMobile != mobile) return Toast.fail("手机号与获取短信手机号不符")

     // 生成2位随机字母（a-z）
     const randomChars = String.fromCharCode(
      97 + Math.floor(Math.random() * 26), // 第一位字母
      97 + Math.floor(Math.random() * 26)  // 第二位字母
    );

    const res = await reqConsumerRegister({
      username : randomChars+mobile.slice(-4),//随机2为字母+手机号后四位
      nickname,
      passWord: pwd1,
      verifyPassWord: pwd1,
      mobile,
      smsCode,
      // role: radio
    })
    console.log(res, 'res11');
    if (res.code != 20000) return showMsg(res.message);
    Toast.success("注册成功")
    this.setData({
      confirmButtonDisabled: true
    })
    this.loginFun(randomChars+mobile.slice(-4), pwd1)
    // setTimeout(() => {
    //     this.setData({
    //         confirmButtonDisabled: false
    //     })
    //     wx.navigateBack({
    //         delta: 1,
    //     })
    // }, 1500)
  },

  // 注册成功立即登录
  async loginFun(username, password) {
    const res1 = await reqLogin({
      username,
      password
    })
    if (res1.code != 20000) return Toast.fail({
      message: res1.message,
    });
    let {
      id: userId,
      token
    } = res1.data.row
    app.globalData.userId = userId
    wx.setStorageSync('userId', userId);
    app.globalData.token = token
    wx.setStorageSync('token', token);
    this.getUserInfo(userId) //获取用户信息
  },
  // 获取个人信息
  async getUserInfo(id) {
    const res = await reqUserInfo(id)
    if (res.code != 20000) return
    let {
      mobile,
      nickname,
      tenantId,
      username,
      idCard,
      openId,
      wxNickName
    } = res.data.row

    let {
      name: rolename,
      description: descriptionRole
    } = res.data.row.role


    app.globalData.mobile = mobile
    wx.setStorageSync('mobile', mobile);
    app.globalData.nickname = nickname
    wx.setStorageSync('nickname', nickname);
    app.globalData.tenantId = tenantId
    wx.setStorageSync('tenantId', tenantId);
    app.globalData.username = username
    wx.setStorageSync('username', username);
    app.globalData.idCard = idCard
    wx.setStorageSync('idCard', idCard);

    app.globalData.openId = openId
    wx.setStorageSync('openId', openId);
    app.globalData.wxNickName = wxNickName
    wx.setStorageSync('wxNickName', wxNickName);

    app.globalData.rolename = rolename
    wx.setStorageSync('rolename', rolename);
    app.globalData.descriptionRole = descriptionRole
    wx.setStorageSync('descriptionRole', descriptionRole);
    setTimeout(()=>{
      wx.switchTab({
        url: '/pages/index/index',
      })
    },1500)
    // if (rolename == 'NORMAL_USER') {
    //   // 业主不需要选择单位
    //   app.globalData.isProprietor = true
    //   wx.setStorageSync('isProprietor', true);
    //   wx.switchTab({
    //     url: '/pages/index/index',
    //   })
    //   return;
    // }
    // app.globalData.isProprietor = false
    // wx.setStorageSync('isProprietor', false);
    // wx.navigateTo({
    //   url: `/pages/personal-inside-page/org/org`,
    // })
    // wx.redirectTo({
    //     url: '/pages/personal-inside-page/org-addOrCreate/org-addOrCreate',
    // })
  },
  backLogin() {
    wx.reLaunch({
      url: '/pages/login/login',
    })
  },
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },
})